package zjc.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import zjc.dao.UserDao;
import zjc.domain.User;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired(required = false)
    private JdbcTemplate jdbcTemplate;

    @Override
    public void save(User user) {
        String sql = "INSERT INTO user(username,password) VALUES(?,?)";
        jdbcTemplate.update(sql,user.getUsername(),user.getPassword());
    }

    @Override
    public void update(User user) {
        String sql = "UPDATE user SET username=?,password=? WHERE id=?";
        jdbcTemplate.update(sql,user.getUsername(),user.getPassword(),user.getId());
    }

    @Override
    public void delete(Long id) {
        String sql = "DELETE FROM user WHERE id=?";
        jdbcTemplate.update(sql,id);
    }

    @Override
    public User findById(Long id) {
        String sql = "SELECT * FROM user WHERE id=?";
        System.out.println("sql");
        System.out.println(sql);
        return jdbcTemplate.queryForObject(sql,new Object[]{id},new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public List<User> findAll() {
        String sql = "SELECT * FROM user";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class));
    }
}
